package event

import (
	"beergo/app/check/models"
	"beergo/lib/event"
	"fmt"
	"github.com/beego/beego/v2/server/web/context"
)

func init() {
	event.ListenJoin("check.AfterCategoryCreate check.AfterCategoryUpdate", func(v interface{}, ctx *context.Context) {
		md,ok:=v.(*models.Category)
		if ok {
			//md.Link = getParent(md)
			//md.SetEventOff()
			//md.Save()
			//println(md)
			updateLink(md)
		}
	})
}

func updateLink(model *models.Category) {
	model.Link = getParent(model)
	model.SetEventOff()
	model.Save()
	model.Load("Children")
	for _, child := range model.Children {
		updateLink(child)
	}

}

func getParent(model *models.Category)string{
	model.Read()
	if model.Parent == nil || model.Parent.Id == 0 {
		return fmt.Sprintf("|%d|",model.Id)
	}else {
		model.Load("Parent")
		return getParent(model.Parent) + fmt.Sprintf("|%d|",model.Id)
	}
}